﻿using HomagChina.Basic.CCT.Db.CCT_Db;
using HomagChina.CCT.DataTypeModel;
using HomagChina.CCT.Router;
using HomagChina.CCT.Views;
using HomagGroup.Base;
using HomagGroup.Base.UI;
using HomagGroup.Base.UI.Controls;
using HomagGroup.Base.UI.Themes.Resources;
using HomagGroup.Base.UI.Windows;
using Proxy;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Shapes;
using System.Windows.Threading;
using static HomagChina.CCT.ProcessResourceInternal;
using localText = Proxy.Properties.Resources;

namespace HomagChina.CCT.ViewModels
{
    public class HomeViewModel : HomagGroup.Base.UI.NotifyPropertyChangedBase
    {
        #region Command

        public RelayCommand ActionButtoClick { get; }
        public RelayCommand ClickInFeed { get; }
        public RelayCommand ClickOutFeed { get; }
        public RelayCommand ClickDRILLTEQ_1 { get; }
        public RelayCommand ClickDRILLTEQ_2 { get; }
        public RelayCommand ClickCancelAll { get; }
        public RelayCommand ClickRunEmpty { get; }
        public RelayCommand EditCommand { get; }
        public RelayCommand DeleteCommand { get; }
        public RelayCommand UnLoadedCommand { get; }
        public RelayCommand LoadedCommand { get; }

        #endregion Command

        #region Conponents

        public string CurrentAdress { get; set; }

        public IDictionary<int, Brush> StatusDictionary { get; set; } = new Dictionary<int, Brush>
            {
                { 0, Application.Current.TryFindResource(HomagGroup.Base.UI.Themes.Resources.InternalKeys.TableFinishedStateImage) as Brush },
                { 1, Application.Current.TryFindResource(HomagGroup.Base.UI.Themes.Resources.InternalKeys.TableErrorStateImage) as Brush }
            };

        private int _TotalParts;

        public int TotalParts
        {
            get => _TotalParts;
            set { _TotalParts = value; OnPropertyChanged(); }
        }

        private DeviceState _InFeedState = Globle.isInfeedAreaActive == true ? DeviceState.Ok : DeviceState.Off;

        public DeviceState InFeedState
        {
            get => _InFeedState;
            set { _InFeedState = value; OnPropertyChanged(); }
        }

        private DeviceState _OutFeedState = Globle.isOutfeedAreaActive == true ? DeviceState.Ok : DeviceState.Off;

        public DeviceState OutFeedState
        {
            get => _OutFeedState;
            set { _OutFeedState = value; OnPropertyChanged(); }
        }

        private DeviceState _DRILLTEQState_1 = Globle.isDRILLTEQActive_1 == true ? DeviceState.Ok : DeviceState.Off;

        public DeviceState DRILLTEQState_1
        {
            get => _DRILLTEQState_1;
            set { _DRILLTEQState_1 = value; OnPropertyChanged(); }
        }

        private DeviceState _DRILLTEQState_2 = Globle.isDRILLTEQActive_2 == true ? DeviceState.Ok : DeviceState.Off;

        public DeviceState DRILLTEQState_2
        {
            get => _DRILLTEQState_2;
            set { _DRILLTEQState_2 = value; OnPropertyChanged(); }
        }

        private ObservableCollection<BoardInfoModel> list_BoardInfoModel;

        public ObservableCollection<BoardInfoModel> List_BoardInfoModel
        {
            get => list_BoardInfoModel;
            set { list_BoardInfoModel = value; OnPropertyChanged(); }
        }

        private List<View_TransOnlineRecordsDetail> _list_TransOnLineModel;

        public List<View_TransOnlineRecordsDetail> list_TransOnLineModel
        {
            get => _list_TransOnLineModel;
            set { _list_TransOnLineModel = value; OnPropertyChanged(); }
        }

        public DropDownList dropDownList { get; set; }

        #region ToggleSwitch

        private bool _InFeedCheck = Globle.isInfeedAreaActive == true ? true : false;

        public bool InFeedCheck
        {
            get => _InFeedCheck;
            set { _InFeedCheck = value; OnPropertyChanged(); }
        }

        private bool _InFeedEnable = true;

        public bool InFeedEnable
        {
            get => _InFeedEnable;
            set { _InFeedEnable = value; OnPropertyChanged(); }
        }

        private bool _OutFeedCheck = Globle.isOutfeedAreaActive == true ? true : false;

        public bool OutFeedCheck
        {
            get => _OutFeedCheck;
            set { _OutFeedCheck = value; OnPropertyChanged(); }
        }

        private bool _OutFeedEnable = true;

        public bool OutFeedEnable
        {
            get => _OutFeedEnable;
            set { _OutFeedEnable = value; OnPropertyChanged(); }
        }

        private bool _DRILLTEQCheck_1 = Globle.isDRILLTEQActive_1 == true ? true : false;

        public bool DRILLTEQCheck_1
        {
            get => _DRILLTEQCheck_1;
            set { _DRILLTEQCheck_1 = value; OnPropertyChanged(); }
        }

        private bool _DRILLTEQCheckEnable_1 = true;

        public bool DRILLTEQCheckEnable_1
        {
            get => _DRILLTEQCheckEnable_1;
            set { _DRILLTEQCheckEnable_1 = value; OnPropertyChanged(); }
        }

        private bool _DRILLTEQCheck_2 = Globle.isDRILLTEQActive_2 == true ? true : false;

        public bool DRILLTEQCheck_2
        {
            get => _DRILLTEQCheck_2;
            set { _DRILLTEQCheck_2 = value; OnPropertyChanged(); }
        }

        private bool _DRILLTEQCheckEnable_2 = true;

        public bool DRILLTEQCheckEnable_2
        {
            get => _DRILLTEQCheckEnable_2;
            set { _DRILLTEQCheckEnable_2 = value; OnPropertyChanged(); }
        }

        #endregion ToggleSwitch

        private bool _RunEmptyCheck;

        public bool RunEmptyCheck
        {
            get => _RunEmptyCheck;
            set { _RunEmptyCheck = value; OnPropertyChanged(); }
        }

        private Canvas _BoardsCanvasView = new Canvas();

        public Canvas BoardsCanvasView
        {
            get => _BoardsCanvasView;
            set { _BoardsCanvasView = value; OnPropertyChanged(); }
        }

        public List<T_LocationInfo> LocationDetailInfo;

        /// <summary>
        /// Dropdown list
        /// </summary>
        private object _SelectedValue;

        public object SelectedValue
        {
            get => _SelectedValue;
            set
            {
                _SelectedValue = value;
                Globle.OpreationMode = value.ToString();
                OnPropertyChanged();
            }
        }

        #region 属性

        private Canvas _warehouse = new Canvas();

        public Canvas Warehouse
        {
            get => _warehouse;
            set { _warehouse = value; OnPropertyChanged(); }
        }

        private Canvas _lead;

        public Canvas Lead
        {
            get => _lead;
            set { _lead = value; OnPropertyChanged(); }
        }

        public Dictionary<string, StorageDataModel> StorageDataModels = new Dictionary<string, StorageDataModel>();

        #endregion 属性

        #endregion Conponents

        #region Handle

        private CommonHandle Handle_Common;
        private InsertInfoHandle Handle_Insert;
        private SearchInfoHandle Handle_Search;
        private DeleteInfoHandle Handle_Delete;
        private RunEmptyHandle Handle_RunEmpty;

        #endregion Handle

        private DispatcherTimer UpdateSessionTimer;

        public HomeViewModel()
        {
            UIAdjustments.CurrentThreadLanguageManager.CultureChanged += NavigateServices.Instance.LanguageManagerCultureChanged;
            ClickInFeed = new RelayCommand(ClickInFeedCommand);
            ClickOutFeed = new RelayCommand(ClickOutFeedCommand);
            ClickDRILLTEQ_1 = new RelayCommand(ClickDRILLTEQCommand_1);
            ClickDRILLTEQ_2 = new RelayCommand(ClickDRILLTEQCommand_2);
            ActionButtoClick = new RelayCommand(ActionButtoClickCommand);

            ClickCancelAll = new RelayCommand(ClickCancelAllCommand);
            ClickRunEmpty = new RelayCommand(ClickRunEmptyCommand);
            EditCommand = new RelayCommand(EditBoardInfo);
            DeleteCommand = new RelayCommand(DeleteBoardInfo);
            LoadedCommand = new RelayCommand(ViewloadedCommand);
            UnLoadedCommand = new RelayCommand(ViewUnloadedCommand);

            Handle_Common = new CommonHandle();
            Handle_Insert = new InsertInfoHandle();
            Handle_Search = new SearchInfoHandle();
            Handle_Delete = new DeleteInfoHandle();
            Handle_RunEmpty = new RunEmptyHandle();
            LoadDropDownList();
            UpdateSessionTimer = new DispatcherTimer
            {
                Interval = TimeSpan.FromMilliseconds(1200)
            };
        }

        /// <summary>
        ///
        /// </summary>
        private void ViewloadedCommand()
        {
            Refresh();
            CreateImageCanvasView();
            CreateSectionCanvasView();
            LinkageWithUI();
        }

        /// <summary>
        /// Unloaded
        /// </summary>
        private void ViewUnloadedCommand()
        {
            UpdateSessionTimer.Stop();
        }

        public void Refresh()
        {
            UpdateSessionTimer.Tick += (sender, args) =>
            {
                LocationDetailInfo = Handle_Search.GetLocationDetailInfo(true);
                List_BoardInfoModel = Handle_Search.GetTransOnLineInfo();
                TotalParts = Handle_Search.GetTotalPartsCount();
                BoardsCanvasView.Children.Clear();
                Warehouse.Children.Remove(BoardsCanvasView);
                if (List_BoardInfoModel != null)
                {
                    foreach (var item in List_BoardInfoModel)
                    {
                        if (item.Length != null && item.Width != null)
                        {
                            Rectangle rectangle = new Rectangle
                            {
                                Uid = item.Reference,
                                Width = (float)item.Length / 20,
                                Height = (float)item.Width / 20,
                                Fill = GetHexadecimalColor("#d5771e"),
                                ToolTip = new TextBlock()
                                {
                                    Text = "Reference:" + item.Reference + "\n"
                                        + "Length:" + item.Length + "\n"
                                        + "Width:" + item.Width + "\n"
                                        + "Thickness:" + item.Thickness,
                                    FontSize = 13,
                                    FontFamily = new FontFamily("Microsoft YaHei"),
                                    HorizontalAlignment = HorizontalAlignment.Center,
                                    VerticalAlignment = VerticalAlignment.Center
                                },
                                Opacity = item.Location.Contains("BF") ? 0.6 : 1
                            };
                            if (item.Location.Contains('R'))
                            {
                                Canvas.SetBottom(rectangle, (float)LocationDetailInfo.Find(s => s.Position == item.Location).PartsCoor_Top);
                            }
                            else
                            {
                                Canvas.SetTop(rectangle, (float)LocationDetailInfo.Find(s => s.Position == item.Location).PartsCoor_Top);
                            }
                            Canvas.SetRight(rectangle, (float)LocationDetailInfo.Find(s => s.Position == item.Location).PartsCoor_Left);

                            Canvas.SetZIndex(rectangle, (int)LocationDetailInfo.Find(s => s.Position == item.Location).PartsCoor_ZIndex);

                            rectangle.MouseRightButtonDown += ModifyPlate;
                            BoardsCanvasView.Children.Add(rectangle);
                        }
                    }
                    Warehouse.Children.Add(BoardsCanvasView);
                }
            };
            UpdateSessionTimer.Start();
        }

        public void AddHomeAddEngineeringOrder()
        {
            HomePlateDialogViewModel HomeAddPlateViewModel = new HomePlateDialogViewModel(null, false, true);
            UIAdjustments.CurrentThreadDialogManager.ShowDialog<HomeAddPlate>(HomeAddPlateViewModel, null);
        }

        #region Canvas

        /// <summary>
        /// 创建图片画布
        /// </summary>
        public void CreateImageCanvasView()
        {
            List<T_MachinePostionInfo> MachineList = Handle_Search.GetMachinePostionInfo();
            foreach (var item in MachineList)
            {
                Rectangle ImageRectangle = new Rectangle
                {
                    Uid = item.MachinePostion,
                    Width = item.MachineWidth,
                    Height = item.MachineHeight,
                    Fill = BitMapConvertsImageBrush(item.MachineImagePath),
                    Opacity = item.MachineImageOpactity
                };
                StorageDataModels.Add(item.MachinePostion, new StorageDataModel
                {
                    Rectangle = ImageRectangle,
                    info = item
                });

                if (ImageRectangle.Uid == "H330-1")
                {
                    ImageRectangle.MouseLeftButtonDown += AddPlate;
                }

                Canvas.SetLeft(ImageRectangle, item.Xposition);
                Canvas.SetTop(ImageRectangle, item.Yposition);
                Warehouse.Children.Add(ImageRectangle);
            }
        }

        /// <summary>
        /// 创建点位画布
        /// </summary>
        public void CreateSectionCanvasView()
        {
            Canvas SectionCanvasView = new Canvas();
            LocationDetailInfo = Handle_Search.GetLocationDetailInfo(true);

            ActionButton actionButton = new ActionButton
            {
                Image = GetIconBrush(Icon.Refresh),
                IsLabelVisible = false,
                Command = ActionButtoClick
            };

            foreach (var item in LocationDetailInfo)
            {
                if (item.Area.Equals("Machine"))
                {
                    continue;
                }
                var grid = new Grid();
                Ellipse container = new Ellipse
                {
                    Width = 50,
                    Height = 50,
                    Fill = Brushes.White,
                    Stroke = Brushes.Green,
                    StrokeThickness = 3,
                };

                TextBlock textBlock = new TextBlock
                {
                    Text = item.Position,
                    Foreground = Brushes.Green,
                    Background = Brushes.White,
                    FontSize = 13,

                    FontWeight = FontWeights.Bold,
                    HorizontalAlignment = HorizontalAlignment.Center,
                    VerticalAlignment = VerticalAlignment.Center
                };
                grid.Children.Add(container);
                grid.Children.Add(textBlock);
                Canvas.SetLeft(grid, (float)item.ComponentsCoor_Left);
                Canvas.SetTop(grid, (float)item.ComponentsCoor_Top);
                Canvas.SetZIndex(grid, 100000);
                SectionCanvasView.Children.Add(grid);
            }
            Warehouse.Children.Add(SectionCanvasView);
            Canvas.SetLeft(actionButton, 0);
            Canvas.SetTop(actionButton, 0);
            Canvas.SetZIndex(actionButton, 100000);
            Warehouse.Children.Add(actionButton);
        }

        private void ActionButtoClickCommand()
        {
            Handle_Delete.DeleteOnLineRecords();
        }


        private void LinkageWithUI()
        {
            this.InFeedCheck = Globle.isInfeedAreaActive;
            this.InFeedState = Globle.isInfeedAreaActive ? DeviceState.Ok : DeviceState.Off;
            this.OutFeedCheck = Globle.isOutfeedAreaActive;
            this.OutFeedState = Globle.isOutfeedAreaActive ? DeviceState.Ok : DeviceState.Off;
            this.DRILLTEQCheck_1 = Globle.isDRILLTEQActive_1;
            this.DRILLTEQState_1 = Globle.isDRILLTEQActive_1 ? DeviceState.Ok : DeviceState.Off;
            Warehouse.Children[1].Opacity = Globle.isDRILLTEQActive_1 ? 1 : 0.3;
        }

        #endregion Canvas

        #region DropDownList

        /// <summary>
        /// 加载DropDownList内容
        /// Load the DropDownList
        /// </summary>
        public void LoadDropDownList()
        {
            dropDownList = new DropDownList();
            var Modes = new List<string>() { { "Auto" } };//, { "Project" } { "Project_A" },
            dropDownList.ItemsSource = (Modes);
            dropDownList.SelectedValue = Globle.OpreationMode.ToString();
            dropDownList.SelectionChanged += DropDownList_SelectionChanged;
        }

        /// <summary>
        /// DropDownList 选择变化事件
        /// SelectionChanged of DropDownList
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DropDownList_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            SelectedValue = ((DropDownList)sender).SelectedItem.ToString();
        }

        #endregion DropDownList

        #region Board

        /// <summary>
        /// 板件数据删除
        /// Delete the board information
        /// </summary>
        /// <param name="obj"></param>
        private void DeleteBoardInfo(object obj)
        {
            if (HomagGroup.Base.UI.Windows.MessageBox.Show(localText.Delete_Tip, localText.Prompt_message, MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.OK)
            {
                BoardInfoModel BoardInfo = (BoardInfoModel)obj;
                if (BoardInfo == null)
                {
                    return;
                }
                if (Handle_Delete.DeleteBoardInfoByUpi(BoardInfo.Reference))
                {
                    HomagGroup.Base.UI.Windows.MessageBox.Show(localText.Deleted_successfully);
                }
            }
        }

        /// <summary>
        /// 板件数据编辑
        /// Edit the board information
        /// </summary>
        /// <param name="SelectItem"></param>
        private void EditBoardInfo(object SelectItem)
        {
            var SelectedItem = SelectItem as BoardInfoModel;
            if (SelectedItem != null)
            {
                HomePlateDialogViewModel HomeAddPlateViewModel = new HomePlateDialogViewModel(SelectedItem as BoardInfoModel, true);
                UIAdjustments.CurrentThreadDialogManager.ShowDialog<HomeAddPlate>(HomeAddPlateViewModel, null);
            }
        }

        /// <summary>
        /// 单击视图添加板件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddPlate(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            CurrentAdress = ((Rectangle)sender).Uid;
            HomePlateDialogViewModel HomeAddPlateViewModel = new HomePlateDialogViewModel(null, false);
            UIAdjustments.CurrentThreadDialogManager.ShowDialog<HomeAddPlate>(HomeAddPlateViewModel, null);
        }

        private void HandleDetailInfo(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            CurrentAdress = ((Rectangle)sender).Uid;
            HomeCacheDetailViewModel homeCacheDetailViewModel = new HomeCacheDetailViewModel();
            UIAdjustments.CurrentThreadDialogManager.ShowDialog<HomeCacheDetail>(homeCacheDetailViewModel, null);
        }

        private void ModifyPlate(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            BoardInfoModel boardInfoModel = null;
            boardInfoModel = List_BoardInfoModel.Where(s => s.Reference == ((Rectangle)sender).Uid).FirstOrDefault();
            HomePlateDialogViewModel HomeAddPlateViewModel = new HomePlateDialogViewModel(boardInfoModel, true);
            UIAdjustments.CurrentThreadDialogManager.ShowDialog<HomeAddPlate>(HomeAddPlateViewModel, null);
        }

        /// <summary>
        ///
        /// </summary>
        /// <param name="boardInfoModel"></param>
        public void AutomaticRunningBoards(float Length, float Width)
        {
            Rectangle rectangle = new Rectangle
            {
                Width = (double)Width / 10,
                Height = (double)Length / 10,
                Fill = GetHexadecimalColor("#d5771e"),
            };

            Canvas.SetLeft(rectangle, StorageDataModels[CurrentAdress].info.Xposition + StorageDataModels[CurrentAdress].info.MachineWidth - 50);
            Canvas.SetTop(rectangle, StorageDataModels[CurrentAdress].info.Yposition);
            Canvas.SetZIndex(rectangle, 10000);
            Warehouse.Children.Add(rectangle);
        }

        #endregion Board

        #region Infeed

        /// <summary>
        /// 入库功能开启
        /// Open the infeed function
        /// </summary>
        public void ClickInFeedCommand()
        {
            if (this.InFeedCheck)
            {
                ActivatedInfeed();
                if (!Globle.isInfeedAreaActive)
                {
                    Globle.isInfeedAreaActive = true;
                }
            }
            else
            {
                UnactivatedInfeed();
            }
        }

        public void ActivatedInfeed()
        {
            this.InFeedCheck = true;
            this.InFeedState = DeviceState.Ok;
            this.InFeedEnable = RunEmptyCheck ? false : true;
        }

        public void UnactivatedInfeed()
        {
            this.InFeedCheck = false;
            this.InFeedState = DeviceState.Off;
            this.InFeedEnable = RunEmptyCheck ? false : true;
            Globle.isInfeedAreaActive = false;
        }

        #endregion Infeed

        #region Outfeed

        /// <summary>
        /// 出库功能开启
        /// Open the outfeed function
        /// </summary>
        public void ClickOutFeedCommand()
        {
            if (this.OutFeedCheck)
            {
                ActivatedOutfeed();
                if (!Globle.isOutfeedAreaActive)
                {
                    Globle.isOutfeedAreaActive = true;
                }
            }
            else
            {
                UnactivatedOutfeed();
            }
        }

        public void ActivatedOutfeed()
        {
            this.OutFeedCheck = true;
            this.OutFeedState = DeviceState.Ok;
            this.OutFeedEnable = RunEmptyCheck ? false : true;
        }

        public void UnactivatedOutfeed()
        {
            this.OutFeedCheck = false;
            this.OutFeedState = DeviceState.Off;
            this.OutFeedEnable = RunEmptyCheck ? false : true;
            Globle.isOutfeedAreaActive = false;
        }

        #endregion Outfeed

        #region H330

        /// <summary>
        /// H330-1 功能开启
        /// Open the H330-1
        /// </summary>
        public void ClickDRILLTEQCommand_1()
        {
            Globle.isDRILLTEQActive_1 = DRILLTEQCheck_1;
            DRILLTEQState_1 = DRILLTEQCheck_1 ? DeviceState.Ok : DeviceState.Off;
            Warehouse.Children[1].Opacity = DRILLTEQCheck_1 ? 1 : 0.3;
        }

        /// <summary>
        /// H330-2 功能开启
        /// Open the H330-2
        /// </summary>
        public void ClickDRILLTEQCommand_2()
        {
            Globle.isDRILLTEQActive_2 = DRILLTEQCheck_2;
            DRILLTEQState_2 = DRILLTEQCheck_2 ? DeviceState.Ok : DeviceState.Off;
            Warehouse.Children[7].Opacity = DRILLTEQCheck_2 ? 1 : 0.3;
        }

        #endregion H330

        #region Cancel All

        /// <summary>
        /// 取消所有功能点击事件
        /// Cancel all function
        /// </summary>
        public void ClickCancelAllCommand()
        {
            CancelAll();
        }

        /// <summary>
        /// 取消所有功能
        /// </summary>
        public void CancelAll()
        {
            UnactivatedRunEmpty();
            UnactivatedInfeed();
            UnactivatedOutfeed();
        }

        #endregion Cancel All

        #region Run Empty

        /// <summary>
        /// 清空线体所有板件
        /// Empty all the parts of the line
        /// </summary>
        public void ClickRunEmptyCommand()
        {
            ActivatedInfeed();
            ActivatedOutfeed();

            if (RunEmptyCheck)
            {
                Globle.isRunEmptyActive = true;
                Task.Factory.StartNew(async () =>
                {
                    string callBackMsg = await Handle_RunEmpty.RunEmpty();
                    CancelAll();
                    HomagGroup.Base.UI.Windows.MessageBox.Show(LocalizedText.CreateFromResourceManager(Proxy.Properties.Resources.ResourceManager, callBackMsg).ToString());
                });
            }
            else
            {
                Globle.isRunEmptyActive = false;
            }
        }

        /// <summary>
        ///
        /// </summary>
        public void UnactivatedRunEmpty()
        {
            RunEmptyCheck = false;
            Globle.isRunEmptyActive = false;
        }

        #endregion Run Empty

        public void HandleOpenMprFile()
        {
            //var data = new FileDialogData()
            //{
            //    InitialDirectory = Directory.GetCurrentDirectory(),
            //    Features = FileDialogData.FeaturesModes.CanCreateFolders
            //};
            //if (UIAdjustments.CurrentThreadDialogManager.FileDialog.SelectDirectory(Application.Current.MainWindow, data) == true)
            //{
            //var Path = ConfigurationManager.AppSettings["CsvPath"];
            //new DealWithFiles().DealWithBoardInfoFiles();
            //}
        }
    }
}